﻿using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

[RequireComponent(typeof(Graphic))]
public class KeepPressButtonEx : ButtonEx
{
    [SerializeField]
    public float keepPressStartTime = 0.5f;
    [SerializeField] 
    public float keepPressInterval = 0.1f;

    Action keepPressCallBack = delegate { };
    
    private bool isKeepPress = false;
    private float m_t = -1;
    protected void Update()
    {
        if (isKeepPress)
        {
            m_t = m_t - Time.deltaTime;
            if (m_t <= 0)
            {
                keepPressCallBack?.Invoke();
                m_t = keepPressInterval;
            }
        }
    }

    protected override void OnEnable()
    {
        base.OnEnable();
        ClearKeepPress();
    }
    
    protected override void OnDestroy()
    {
        base.OnDestroy();
        ClearKeepPress();
        keepPressCallBack = null;
    }

    public override void OnPointerDown(PointerEventData eventData)
    {
        base.OnPointerDown(eventData);
        
        if (eventData.currentInputModule.input.touchCount > 1)
        {
            return;
        }
        StartKeepPress();
    }

    public override void OnPointerUp(PointerEventData eventData)
    {
        base.OnPointerUp(eventData);
        ClearKeepPress();
    }

    public void AddKeepPressEvent(Action action)
    {
        keepPressCallBack = action;
    }

    private void ClearKeepPress()
    {
        isKeepPress = false;
    }

    private void StartKeepPress()
    {
        isKeepPress = true;
        m_t = keepPressStartTime;
    }
}